package com.tedu.sp06.filter;
/*
  zuul网关过滤器配置
  定义过滤器，继承 ZuulFilter
 */
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.tedu.web.util.JsonResult;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {
    //过滤器类型 ： pre , routing, post , error
    @Override
    public String filterType() {
        //return "pre";
        return FilterConstants.PRE_TYPE;
    }
   //过滤器顺序
    @Override
    public int filterOrder() {
        //有5个默认过滤器，放到最后一个
        return 6;
    }
      //是否执行过滤代码
    @Override
    public boolean shouldFilter() {
        //获取上下文对象
        RequestContext context = RequestContext.getCurrentContext();
        //获取当前服务id===serviceId
        String serviceId = (String) context.get(FilterConstants.SERVICE_ID_KEY);//
        //判断是否为商品服务

        return "item-service".equals(serviceId);
    }
       //
    @Override
    public Object run() throws ZuulException {
        //获取上下文对象
        RequestContext context = RequestContext.getCurrentContext();

        //获取request对象
        HttpServletRequest request = context.getRequest();
        //接收token参数
        String token = request.getParameter("token");
        //是否携带token，
        if (StringUtils.isBlank(token)){ // token=null,token="" ,token="  "
            //阻止调用
            context.setSendZuulResponse(false);
            //返回响应
            context.addZuulResponseHeader("Content-Type", "application/json;charset=UTF-8");
            context.setResponseBody(JsonResult.err().code(400).msg("未登录").toString());

        }
        return null;//目前该返回值没有被使用

    }
}
